<?php
namespace app\api\model;

use think\Db;

class ArticleModel
{
    /**
     * 单例模式
     * @return ArticleModel
     *
     */
    public static function instance(){
        static $m = null;
        if(!$m){
            $m = new ArticleModel();
        }
        return $m;
    }

    /**
     * 展示信息  api
     */
    public function getOne($id){
        $res = Db::name('article')->field(['id','name','content'])->where(['id'=>$id])->find();
        return $res;
    }
    /*
    *搜索
    */
    public function getList($data){
        $data['name']  = isset($data['name']) ? $data['name'] : '';
        $data['cat']   = isset($data['cat'])  ? $data['cat']  : '';
        $data['cat2']  = isset($data['cat2']) ? $data['cat2'] : '';
        $data['cat3']  = isset($data['cat3']) ? $data['cat3'] : '';
        $page          = isset($data['step']) ? $data['step'] : 0;
        $list          = '';
        $step          = 20;
        $start         = $page*$step;

        if ($data['name'] != '') {
            $list = Db::name('article')->where(['del'=>0])->order('id desc')->where('name','like','%'.$data['name'].'%')->limit($start,$step)->select();
            $count = count(Db::name('article')->where(['del'=>0])->field('id')->where('name','like','%'.$data['name'].'%')->select());
        }else{
            $where = '';
            if ($data['cat'] != '') {
                $where = 'cat ='.$data['cat'];
                if($data['cat2'] != ''){
                    $where .= ' AND cat2 ='.$data['cat2'];
                    if($data['cat3'] != ''){
                        $where .= ' AND cat3 ='.$data['cat3'];
                    }
                }
            }
            $list = Db::name('article')->where(['del'=>0])->where($where)->order('id desc')->limit($start,$step)->select();
            $count = count(Db::name('article')->where(['del'=>0])->where($where)->field('id')->select());
        }
        return [$list,$page,$count];
    }

    /*
    *获取分类，包括非信息展示
    */
    public function getCat(){
        $list = Db::name('menus')->where(['bid'=>123,'status'=>1])->field(['tid','name'])->select();
        $commType = Db::name('commType');
        foreach ($list as $k => $v) {
            $menu2 = $commType->where(['tid'=>$v['tid'],'level'=>0,'status'=>1])->order('solt desc')->field(['ptid','name','tid'])->select();
            $list[$k]['sub'] = $menu2;
            foreach ($list[$k]['sub'] as $key => $value) {
                $menu3 = $commType->where(['level'=>1,'pid'=>$value['ptid'],'status'=>1])->order('solt desc')->field(['ptid','name','tid','ptid'])->select();
                $list[$k]['sub'][$key]['sub'] = $menu3;
            }
        }
        return $list;
    }    

}
